part of base.temples;

abstract class PagingController<M, S extends PagingState<M>>
    extends GetxController {
  LoadState emptyState = LoadState.State_Loading;

  /// PagingState
  late S pagingState;

  @override
  void onInit() {
    super.onInit();

    /// 保存 State
    pagingState = getState();
  }

  @override
  void onReady() {
    super.onReady();

    /// 进入页面刷新数据
    refreshData();
  }

  /// 刷新数据
  void refreshData() async {
    ///初始化分页数据
    pagingState.tempPage = pagingState.curPage = pagingState.startPage;
    print('开始刷新2');
    _loadData();
  }

  void refreshCompleted() {
    /// 刷新完成
    pagingState.refreshController.refreshCompleted();
  }

  void loadComplete() {
    /// 加载完成
    pagingState.refreshController.loadComplete();
  }

  /// 数据加载
  void _loadData() async {
    loadData(pagingState.tempPage);
  }

  /// 加载更多
  void loadMoreData() async {
    pagingState.tempPage = pagingState.curPage;
    pagingState.tempPage++;
    _loadData();
  }

  /// 最终加载数据的方法
  void loadData(int page);

  /// 获取 State
  S getState();

  set setNewData(List<M> data) => {
        print("newDate"),
        if (pagingState.data.isNotEmpty) {pagingState.data.clear()},
        pagingState.data.addAll(data)
      };

  void error() => {
        /// 大于其实页说明是在加载下一页是造成的失败
        /// 允许加载更多
        if (pagingState.tempPage > pagingState.startPage &&
            pagingState.enableLoadMore)
          {
            pagingState.refreshController.loadFailed(),
          }
      };

  void insertData(int p, List<M> m) {
    pagingState.data.insertAll(p, m);
  }

  void removeData(M m) {
    pagingState.data.remove(m);
  }

  void removeAt(int index) {
    pagingState.data.removeAt(index);
  }

  M elementAt(int index) => pagingState.data.elementAt(index);

  ///刷新状态
  void setData(List<M>? m) {
    print("setData $m");

    /// 刷新完成
    refreshCompleted();

    /// 加载完成
    loadComplete();
    if (m == null) {
      emptyState = LoadState.State_Empty;
    } else {
      if (pagingState.tempPage == pagingState.startPage) {
        if (m.isEmpty) {
          ///如果 header 有数据 列表为空时允许显示
          if (pagingState.headAndEmptyEnable && m.isNotEmpty) {
            emptyState = LoadState.State_Success;
          } else {
            emptyState = LoadState.State_Empty;
          }
        } else {
          emptyState = LoadState.State_Success;
          setNewData = m;
        }
        pagingState.enableLoadMore = m.length < pagingState.pageSize;
      } else {
        pagingState.curPage = pagingState.tempPage;
        if (m.isEmpty) {
          pagingState.refreshController.loadNoData();
        }
        emptyState = LoadState.State_Success;
        pagingState.data.addAll(m);
      }
    }

    /// 更新界面
    update([pagingState.refreshId]);
  }
}
